package service;

import common.Message;
import common.MessageType;
import dao.UserDao;
import entity.User;
import tools.ThreadManage;
import view.ServerView;

import java.util.ArrayList;

public class UserService {

    private UserDao userDao = new UserDao();

    /**
     * 处理用户登录
     *
     * @param qq
     * @param pwd
     * @return 登录成功返回用户对象包含用户名和uid, 登录失败返回null
     */
    public User login(int qq, String pwd) throws RuntimeException {
        // 判断用户登录状态
        User user = userDao.getByQQAndPwd(qq, pwd);
        if (user != null) {
            ServerView.printLog(user.getNickname() + "登录成功");
        }
        return user;
    }

    /**
     * 用户注册
     *
     * @param ru
     * @return
     */
    public User register(User ru) {
        User u = null;
        UserDao userDao = new UserDao();
        int qq = userDao.add(ru);
        if (qq != 0) {
            ServerView.printLog("[" + qq + "]用户注册成功");
            ServerView.showUserList();
            u = userDao.getByQQ(qq);
        }
        return u;
    }

    /**
     * 修改密码
     *
     * @param qq
     * @param pwd
     * @return
     */
    public Boolean changePassword(int qq, String pwd) {
        Boolean aBoolean = new UserDao().updatePwdByQQ(qq, pwd);
        if (aBoolean) {
            ServerView.printLog("[" + qq + "]修改密码成功");
        } else {
            ServerView.printLog("[" + qq + "]修改密码失败");
        }
        return aBoolean;
    }

    /**
     * 获取好友列表
     *
     * @param qq
     * @return
     */
    public void getFriends(int qq) {
        ServerView.printLog("[" + qq + "]请求获取好友列表");
        ArrayList<User> friends = new UserDao().getFriendsByQQ(qq);
        Message message = new Message();
        message.setContent(friends);
        message.setType(MessageType.GET_FRIENDS);
        ServerThread thread = ThreadManage.getThread(qq);
        thread.send(message);
    }

    /**
     * 获取所有用户
     *
     * @return
     */
    public ArrayList<User> getUserList() {
        ArrayList<User> allUser = null;
        allUser = new UserDao().getAllUser();
        return allUser;
    }


    /**
     * 添加好友
     *
     * @param qq
     * @param fqq
     * @return
     */
    public Boolean addFriend(int qq, int fqq) {
        UserDao userDao = new UserDao();
        if (qq == fqq) {
            return false;
        } else if (!userDao.hasFriend(qq, fqq)) {
            return userDao.addFriend(qq, fqq);
        } else {
            return false;
        }
    }

    /**
     * 处理用户下线
     *
     * @param offlineUser
     */
    public void userOffline(User offlineUser) {
        ServerThread thread = ThreadManage.getThread(offlineUser.getQq());
        thread.myStop();
        ThreadManage.removeThread(offlineUser.getQq());
        ServerView.showUserList();
        ServerView.printLog(offlineUser.getNickname() + "下线");
    }

}
